import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { tableConfig, header } from '../data/config'
import { getUrlParam } from '../data/util'
import store from 'store'

const base = url.base,
    getOneHouseHelperPage = request.getOneHouseHelperPage,
    deleteOneHouseHelper = request.deleteOneHouseHelper,
    deleteOneHouseHelpers = request.deleteOneHouseHelpers;

let table,
    storeData;

// 初始化表格
table = $('#table').bootstrapTable($.extend({}, tableConfig, {
    url: base + getOneHouseHelperPage,
    queryParams: function(params) {
        return $.extend({
            currentPage: params.pageNumber,
            pageSize: params.pageSize,
        }, $('#searchForm').serializeObject())
    },
    columns: [
        {
            field: 'checked',
            checkbox: true,
            valign: 'middle',
            title: '选择'
        },
        {
            field: 'url',
            title: '标题名称',
            valign: 'middle',
            align: 'left',
            formatter: function(value, row, index) {
                if(value){
                    let urls=value.slice(1)
                    return `
                    <img  src="${base+urls}" class="img-rounded" style="width:100px;">
                    <span>${row.name}</span>                
                    `;
                }else{
                    return `
                    <button   class="img-rounded" style="width:100px;opacity:0"></button>
                     <span>${row.name}</span>
                     `;
                }
                  
            }
        }, {
            field: 'isRecommend',
            title: '注册推荐信息',
            valign: 'middle',
            formatter: function(index, row) {
                const isRecommend = String(index)
                switch (isRecommend) {
                    case '0':
                        return `<ul style="color:#1890ff">
                            <li>注册推送消息</li>
                        </ul>`
                    case '1':
                        return ''
                }
            }
        }, {
            field: 'status',
            title: '状态',
            valign: 'middle',
            formatter: function(index, row) {
                const status = String(index)
                switch (status) {
                    case '1':
                        return '草稿'
                    case '2':
                        return '已发布'
                    default:
                        return '未知'
                }
            }
        }, {
            field: 'createUserName',
            title: '创建人',
            valign: 'middle'
        }, {
            field: 'rawAddTime',
            title: '创建时间',
            valign: 'middle',
            formatter: (index, row) => {
                let times= parseInt(index)
                return moment(times).format('YYYY-MM-DD HH:mm:ss')
              }
        }, {
            field: 'action',
            valign: 'middle',
            align: 'center',
            title: '操作',
            formatter: function(index, row) {
                if(String(row.status)==='1'){
                    return `<div class="btn-group">                 
                    <button type="button" data-id="${ row.id}" class="btn btn-primary btn-bordered btn-modify">编辑</button>                  
                    <button type="button" data-id="${ row.id}" class="btn btn-primary btn-bordered btn-delete">删除</button>                  
                    <button style="visibility:hidden" type="button" data-id="${ row.id}" class="btn btn-primary btn-bordered btn-preview">预览</button>                  
              </div>`
                }else{
                return `<div class="btn-group">
                      <button type="button" data-id="${ row.id}" class="btn btn-primary btn-bordered btn-preview">预览</button>                  
                      <button type="button" data-id="${ row.id}" class="btn btn-primary btn-bordered btn-modify">编辑</button>                  
                      <button type="button" data-id="${ row.id}" class="btn btn-primary btn-bordered btn-delete">删除</button>                  
                </div>`
                }
            }
        }]
}))

// 点击列表的时候传递数据到全局变量
table.on('click-row.bs.table', (e, data, el) => {
    storeData = data

})

// 初始化日期选择器
$('#rawAddStartTime').datetimepicker({
    format: "yyyy-mm-dd",
    startView: 3,
    minView: 2,
    autoclose: true
});
$('#rawAddEndTime').datetimepicker({
    format: "yyyy-mm-dd",
    startView: 3,
    minView: 2,
    autoclose: true
});

// 搜索
$('#search-btn').on('click', (e) => {
    e.preventDefault();
    table.bootstrapTable('refresh', {
        query: $.extend({
            currentPage: 1,
        }, $('#searchForm').serializeObject())
    })
})

//跳转至修改页
$(document).on('click', '#table .btn-modify', (e) => {
    e.preventDefault()

    store.set('storeData', storeData)
    window.location.href = `./modify.html?id=${storeData.id}`
})

//点击了单个删除
$(document).on('click', '#table .btn-delete', (e) => {
    e.preventDefault()
    let id = $(e.target).attr('data-id');

    bootbox.confirm({
        title: '提示',
        message: `<div>
                <h3 style="margin:.75em 0">是否删除？</h3>
              </div>`,
        buttons: {
            cancel: {
                label: '取消'
            },
            confirm: {
                label: '删除'
            }
        },
        callback: (result) => {
            if (!result) {
                return
            }

            let loading_modal = layer.msg('提交中...', {
                icon: 16,
                time: 0
            })
            // header
            $.ajax({
                url: base + deleteOneHouseHelper,
                headers: header,
                contentType: 'application/json',
                type: 'POST',
                data: JSON.stringify({
                    id: id
                })
            })
                .done(function(res) {

                    if (res.code == 0) {

                        layer.msg('删除成功', {
                            icon: 6
                        })

                        table.bootstrapTable('refresh')

                    } else {
                        layer.msg('删除失败', {
                            icon: 5
                        })
                    }

                })
                .fail(function(res) {

                    layer.msg('删除失败', {
                        icon: 5
                    })

                })
                .always(function(res) {

                    layer.close(loading_modal)
                })
        }
    })
})

// 批量删除
$('#batch_delete').on('click', (e) => {
    e.preventDefault()
  
    let data      = new Array(),
        tit,
        selection = table.bootstrapTable("getAllSelections"),
        i         = 0,
        len       = selection.length;
  
    if (!selection.length) {
      layer.msg('没有选择数据', {
        icon: 5
      })
  
      return
    }
  
    tit = `确认删除<span class="text-danger">【${len}】</span>条数据吗`;
  
    for (; i < len; i++) {
     data.push(selection[i].id)
    }
  
    bootbox.confirm({
      title: '提示',
      message: `<div>
                  <h3 style="margin:.75em 0">${ tit }</h3>
                </div>`,
      buttons: {
        cancel: {
          label: '取消'
        },
        confirm: {
          label: '删除'
        }
      },
      callback: (result) => {
  
        if (!result) {
          return
        }
  
        let loading_modal = layer.msg('删除中...', {
          icon: 16,
          time: 0,
          shade: .5
        });
  
        data = data.join(',');
  
        $.ajax({
          headers: header,
          url: base + deleteOneHouseHelpers,
          contentType: 'application/json',
          type: 'POST',
          data: JSON.stringify({
            ids: data
          })
        })
          .done(function (res) {
  
            if (res.code === 0) {
              layer.msg(res.message ? res.message : '删除成功', {
                icon: 6
              })
            } else {
              layer.msg(res.message ? res.message : '删除失败', {
                icon: 5
              })
            }
            table.bootstrapTable('refresh')
  
          })
          .fail(function (res) {

  
            layer.msg('删除失败', {
              icon: 5
            })
  
          })
          .always(function (res) {
  
            layer.close(loading_modal)

          })
      }
    })
  
  })

//点击预览
$(document).on('click', '#table .btn-preview', (e) => {
    e.preventDefault()
    resetPrePhoneCss();
    updatePreviewHtml();

    $(".preview-layer").show();
})
function resetPrePhoneCss() {
    let dom = $(".preview-phone"),
        dom_left = $(window).width() / 2 - dom.width() / 2,
        dom_top = $(window).height() / 2 - dom.height() / 2,
        css_str = {
            left: dom_left + "px",
            top: dom_top + "px"
        };
    dom.css(css_str);
}

function updatePreviewHtml() {

    let ifr_document = document.getElementById("preview-html").contentWindow.document,
        content = storeData.content===undefined?'':storeData.content;

    //设置正文
    if (ifr_document && content) {
        let ifr_content = $(ifr_document).find(".article-content");
        ifr_content.html(content);
    }
}